package com.longrise.android.byjk.plugins.dealsituation.course.exercises;

import android.os.Handler;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.common.base.BasePresenter;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.event.CourseDetailEvent;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.Constants;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoParams;
import com.longrise.common.datasource.local.sp.CacheUtils;
import com.longrise.common.datasource.remote.LoadDataManager;

import org.greenrobot.eventbus.EventBus;

import java.net.URLEncoder;

/**
 * Created by godliness on 2017/8/18.
 */

public class ExercisesPresenter extends BasePresenter<ExercisesView> {

    private static final String TAG = "ExercisesPresenter";

    public static final int MSG_SHOW_TIPS_DIALOG = 0;
    public static final int MSG_SHOW_BACK_TIPS_DIALOG = 1;

    private final StringBuilder mBuilder = new StringBuilder();
    private final Handler mHandler = new Handler();

    @Override
    protected void init() {
    }

    public void toRequest() {
        final VideoParams vp = initParams();
        if (vp == null) {
            return;
        }
        mView.showLoadingDialog();
        final EntityBean bean = new EntityBean();
        bean.set("urltype", vp.mHasqa ? "khlx" : "mncs");
        EntityBean bean2 = new EntityBean();
        bean2.set("bean", bean);
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl, "bbt_getAppEntryPath", bean2, new LoadDataManager.OnRequestCallListener() {

            @Override
            public void onSuccess(String key, String service, Object result) {
                try {
                    EntityBean resultBean = (EntityBean) result;
                    int resultState = resultBean.getInt("resultstate");
                    if (resultState != 1) {
                        mView.onError();
                        mView.showToast(resultBean.getString("resultdesc"));
                        return;
                    }
                    EntityBean bean1 = resultBean.getBean("result");
                    if (bean1 == null) {
                        return;
                    }
                    parse(bean1, vp.mHasqa);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                mView.onError();
            }

            @Override
            public void onFinished(String key, String service) {
            }

        });
    }

    private void parse(EntityBean bean, boolean hasqa) {
        String url;
        if (hasqa) {
            url = bean.getString("exerciseentryurl");
        } else {
            url = bean.getString("simulationtesturl");
        }
        mView.parse(url);
    }

    /**
     * 模拟测试题地址
     */
    public String packageSimTestUrl(String infodetailsurl) {
        VideoParams vp = initParams();
        if (vp == null) {
            return "";
        }
        mBuilder.append(infodetailsurl);
        mBuilder.append("/@");
        mBuilder.append(vp.mCwid);
        mBuilder.append("/@");
        mBuilder.append(UserInfor.getInstance().getUsersfzh());
        mBuilder.append("/@");
        mBuilder.append(vp.mStudentNo);
        mBuilder.append("/@");
        mBuilder.append(vp.istest);
        mBuilder.append("/@");
        mBuilder.append(vp.recordid);
        mBuilder.append("/@");
        mBuilder.append(UserInfor.getInstance().getUserid());
        mBuilder.append("/@");
        mBuilder.append(vp.mCourseId);
        return mBuilder.toString();
    }

    private VideoParams initParams() {
        VideoParams vp = mView.getParams();
        mBuilder.setLength(0);
        return vp;
    }

    /**
     * 课后习题地址
     */
    public String packageCwidTestUrl(String url) {
        VideoParams vp = initParams();
        if (vp == null) {
            return "";
        }
        mBuilder.append(url);
        mBuilder.append("?uid=");
        mBuilder.append(UserInfor.getInstance().getUserid());  //uid
        mBuilder.append("&cwid=");
        mBuilder.append(vp.mCwid);
        mBuilder.append("&pid=");
        mBuilder.append(vp.mCourseId);
        mBuilder.append("&pname=");
        String paname = CacheUtils.getString(Constants.CourseTest.INTENT_PNAME, "");  //课程名称，CourseFragPresenter 与 DownloadedDetailLFView进行设置了
        try {
            mBuilder.append(!TextUtils.isEmpty(paname) ? URLEncoder.encode(paname, "UTF-8") : "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        mBuilder.append("&stuno=");
        mBuilder.append(vp.mStudentNo);
        mBuilder.append("&cardno=");
        mBuilder.append(UserInfor.getInstance().getUsersfzh());
        return mBuilder.toString();
    }

    private String interceptTitle(String value) {
        if (TextUtils.isEmpty(value)) {
            return "";
        }
        boolean contains = value.contains("&");
        if (!contains) {
            return value;
        }
        String split[] = value.split("&");
        if (split.length > 1) {
            return split[0];
        }
        return value;
    }

    /**
     * ----------------以下为javascriptinterface交互----------------
     * <p>
     * ----------------模拟测试题 获取标题---------------
     */
    @JavascriptInterface
    public void setTitle(final String title) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                String interTitle = interceptTitle(title);
                mView.getTitle(interTitle);
            }
        });
    }

    /**
     * 模拟测试题toast
     */
    @JavascriptInterface
    public void showHintMsg(final String msg) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mView.showToast(msg);
            }
        });
    }

    /**
     * 关闭页面
     */
    @JavascriptInterface
    public void closeSimulationTest() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mView.onBack();
            }
        });
    }

    /**
     * 更新课件状态
     */
    @JavascriptInterface
    public void updateCoursePraxis() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
//                Intent courseIntent = new Intent(MessageConstants.PAY_SUCCESS);
//                courseIntent.putExtra(ReceiverType.RECEIVER_KEY, ReceiverType.REFRESH_DETIAL);
//                mContext.sendBroadcast(courseIntent);

                CourseDetailEvent event = new CourseDetailEvent();
                event.setRefreshDetail(true);
                EventBus.getDefault().post(event);
            }
        });
    }

    /**
     * -------------以下为课后习题-----------------
     */
    @JavascriptInterface
    public void showTipsDialog(final String message) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mView.msgShowTipsDialog(MSG_SHOW_TIPS_DIALOG, message, -1);
            }
        });
    }

    /***/
    @JavascriptInterface
    public void showBackTipsDialog(final String msgStr, final int isfinish) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mView.msgShowTipsDialog(MSG_SHOW_BACK_TIPS_DIALOG, msgStr, isfinish);
            }
        });
    }

    /**
     * ga
     */
    @JavascriptInterface
    public void getDeviceInfor() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                mView.setDeviceInfoForGA();
            }
        });
    }
}
